// miniprogram/pages/NX_selfProject/selfProject.js
import configGantt, {
    getLocalString
} from '../../library/configGantt'
const db = wx.cloud.database();
const app = getApp();
const sysInfo = wx.getSystemInfoSync()
const scaleRate = sysInfo.windowWidth / 750;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        displayId: 'project',
        message: '欢迎回来',
        windowWidth: 750,
        windowHeihgt: 100,
        maskShow: true,
        onShow: false,
        project: [],
        master: [],
        mission: [],
        ganttInit: false,
        gantt: null,
        missionTop: 0,
        maxTop: null,
        scaleRate: 1,
        itemHeight: 152,
        missionListAnime: false,
        listMove: {
            isMove: false,
            startY: 0,
            lastY: 0,
            lastTime: 0,
            speed: 0
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            windowHeight: getApp().globalData.windowHeightRpx,
            scaleRate
        })
        const invite = app.globalData.invite;
        if (invite && invite.invite) {
            wx.navigateTo({
                url: `../NX_joinProject/joinProject?projectId=${invite.projectId}&inviter=${invite.inviter}&time=${invite.time}`
            })
            
            app.globalData.invite = null;
            return;
        }
        if (!app.globalData.userInfo.project.length) {
            try{
                const first=wx.getStorageSync('firstTime');
                if(!first){
                    wx.setStorage({
                        key:'firstTime',
                        data:1
                    })
                    wx.navigateTo({
                        url: '../NX_newProject/newProject',
                    })
                }
            }catch(e){
                console.log(e);
            }
          
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () { },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // setInterval(this.addBar.bind(this),100)

        this.setData({
            onShow: true
        })
        wx.setNavigationBarTitle({
            title: getApp().globalData.userInfo.userName,
        })
        this.init()
    },
    init() {
        this.setData({
            message: '正在拉取数据'
        })
        wx.showNavigationBarLoading();
        return new Promise((resolve, reject) => {
            if (!this.data.onShow) reject('页面不在前台');
            wx.cloud.callFunction({
                name: 'login',
                data: {
                    needDetail: true
                }
            }).then(res => {
                if (res.result && !res.result.err && res.result.userInfo) {
                    console.log(res)
                    getApp().globalData.userInfo = res.result.userInfo
                    const pastFlag = this.data.maskShow;
                    getApp().globalData.selfMission = res.result.mission
                    this.setData({
                        project: res.result.project,
                        master: res.result.master,
                        mission: res.result.mission,
                        maskShow: false,
                    })
                    this.data.maxTop = res.result.mission.length * (this.data.itemHeight * scaleRate) - (getApp().globalData.windowHeight - 50 * scaleRate) * 2 / 3

                    this.setData({
                        message: ''
                    })
                    this.rangeDiluter(null, null, true);
                    if (pastFlag && this.data.mission.length) {
                        this.setData({
                            displayId: 'mission'
                        })
                    }
                    wx.hideNavigationBarLoading();
                    resolve()
                } else {
                    console.log('用户信息获取失败', res.err)
                    // setTimeout(() => this.init(), 5000)
                    this.setData({
                        message: '用户信息获取失败',
                    })
                    wx.hideNavigationBarLoading();
                    reject(res.err)
                }
            })
                .catch(err => {
                    console.log('用户信息获取失败', err)
                    this.setData({
                        message: '获取信息失败',
                    })
                    // setTimeout(() => this.init(), 5000)
                    wx.hideNavigationBarLoading();
                    reject(err)
                })
        })
    },
    questClick(e) {
        const missionId = e.target.dataset.id;
        //遍历ganttList找到任务目标
        const globalData = getApp().globalData
        globalData.tempMissionDetail = null;
        if (this.data.gantt && this.data.gantt.ganttList && this.data.gantt.ganttList.length) {
            for (const ganttRow of this.data.gantt.ganttList) {
                for (const ganttCol of ganttRow) {
                    if (ganttCol._id === missionId) {
                        globalData.tempMissionDetail = ganttCol;
                        break;
                    }
                }
            }
        }
        wx.navigateTo({
            url: '../NX_detailMission/detailMission?master=true&missionId=' + missionId,
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        this.setData({
            // maskShow: true,
            onShow: false
        })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        // this.setData({
        //   message: '正在拉取数据'
        // })
        this.init()
            .then(() => {
                wx.stopPullDownRefresh();
            })
    },
    onswiper(e) {
        this.setData({
            displayId: e.detail.currentItemId
        })
    },
    onClickTab(e) {
        this.setData({
            displayId: e.target.dataset.id
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    starMission(e) {
        for (let quest of this.data.mission) {
            if (quest._id === e.target.dataset.id) {
                quest.star = !quest.star;
                // db.collection('mission').doc(quest._id).update({
                //     data: {
                //         star: quest.star
                //     }
                // })
                // .then(res=>console.log(res))
                wx.cloud.callFunction({
                    name: 'updateMissionInfo',
                    data: {
                        missionId: quest._id,
                        star: quest.star
                    }
                })
                break;
            }
        }
        this.setData({
            mission: this.data.mission
        })
        this.rangeDiluter(null, null, true);
    },
    finMission(e) {
        for (let quest of this.data.mission) {
            if (quest._id === e.target.dataset.id) {
                quest.status = (quest.status == 'done') ? 'doing' : 'done';
                wx.cloud.callFunction({
                    name: 'updateMissionInfo',
                    data: {
                        missionId: quest._id,
                        status: quest.status
                    }
                })
                break;
            }
        }
        this.setData({
            mission: this.data.mission
        })
        this.rangeDiluter(null, null, true);
    },
    ystart(e) {
        if (!e.detail || !e.detail.y) return;
        this.data.listMove = {
            isMove: true,
            startY: e.detail.y,
            lastY: e.detail.y,
            lastTime: e.timeStamp,
            originY: this.data.missionTop,
            speed: 0
        }
        this.setData({
            missionListAnime: false,
        })
    },
    ymove(e) {
        if (this.data.listMove.isMove) {
            this.data.listMove.speed = (e.detail.y - this.data.listMove.lastY) / (e.timeStamp - this.data.listMove.lastTime);
            this.data.listMove.lastY = e.detail.y;
            this.data.listMove.lastTime = e.timeStamp;
            let tempTop = this.data.listMove.originY + this.data.listMove.startY - e.detail.y;
            if (tempTop < 0) tempTop = 0;
            if (this.data.maxTop && tempTop > this.data.maxTop) tempTop = this.data.maxTop;
            this.setData({
                missionTop: tempTop,
                missionListAnime: false,
            })
            this.rangeDiluter();
        }
    },
    yend() {
        if (this.data.listMove.isMove) {
            let missionTop = this.data.missionTop - this.data.listMove.speed * 250;
            if (this.data.maxTop && missionTop > this.data.maxTop) missionTop = this.data.maxTop;
            if (missionTop < 0) missionTop = 0;
            this.setData({
                missionListAnime: true,
            })
            setTimeout(() => {
                this.setData({
                    missionTop
                })
                this.rangeDiluter();

            }, 10)
            this.data.listMove = {
                isMove: false,
                startY: 0,
                lastY: 0,
                lastTime: 0,
                speed: 0
            }

        }
    },
    computeRange() {
        const top = this.data.missionTop / scaleRate;
        const bottom = top + (getApp().globalData.windowHeightRpx - 50) * 2 / 3
        const itemHeight = this.data.itemHeight;
        let start = null;
        let end = null;
        for (let i = 0, j = 0; i < this.data.mission.length; i++ , j += itemHeight) {
            const item = this.data.mission[i];
            const itemTop = j;
            if (itemTop > top - itemHeight / 2 && itemTop + itemHeight / 2 < bottom) {
                //在显示区域内
                if (item.start) {
                    const dateArr = item.start.split('-')
                    dateArr[1]--;
                    const itemStart = new Date(...dateArr).getTime();
                    if (!start || start > itemStart) start = itemStart;
                }
                if (item.end) {
                    const dateArr = item.end.split('-')
                    dateArr[1]--;
                    const itemEnd = new Date(...dateArr).getTime();
                    if (!end || end < itemEnd) end = itemEnd;
                }
            }
        }
        start = getLocalString(new Date(start));
        end = getLocalString(new Date(end));
        return [start, end];
    },
    rangeDiluter(start, end, force = false) {
        // return;
        if (!this.data.mission.length) return;
        if (!rangeTimer || force) {
            clearTimeout(rangeTask);
            rangeTimer = setTimeout(() => rangeTimer = null, 100);
            let nStart, nEnd;
            if (start && end) {
                [nStart, nEnd] = [start, end];
            } else {
                [nStart, nEnd] = this.computeRange();
            }
            if (force || nEnd !== rangeLastEnd || nStart !== rangeLastStart) {
                rangeLastEnd = nEnd;
                rangeLastStart = nStart;
                Promise.resolve().then(() => {
                    configGantt(this.data.mission.filter(a => a.init), null, {
                        mix: true,
                        start: nStart,
                        end: nEnd,
                        limitTimeRange: true
                    }).then(gantt => {
                        // console.log(gantt)
                        if (gantt && gantt.ganttList && gantt.ganttList.length) {
                            this.setData({
                                gantt,
                                ganttInit: true
                            })
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                })
            }
        } else {
            const [newStart, newEnd] = this.computeRange();
            if (end !== newEnd) {
                //置入task
                clearTimeout(rangeTask);
                rangeTask = setTimeout(this.rangeDiluter, 100, newStart, newEnd)
            }

        }
    },
    onShareAppMessage(e) {
        return {
            title: `邀请您使用Nexeam协同小程序`,
            path: `/pages/NX_index/index`,
            imageUrl: '../../images/nexeam_banner.png'
        }
    },
    projectMenu(e) {
        const {
            item,
            role
        } = e.currentTarget.dataset;
        switch (role) {
            case '0':
                wx.showActionSheet({
                    itemList: ['退出项目'],
                    success: res => {
                        if (res.tapIndex === 0) {
                            exitProject()
                        }
                    }
                })
                break;
            case '1':
                wx.showActionSheet({
                    itemList: ['成员管理', '解散项目'],
                    success: res => {
                        if (res.tapIndex === 0) {
                            wx.navigateTo({
                                url: `../NX_detailProjectMember/detailProjectMember?projectId=${item._id}`,
                            })
                        } else if (res.tapIndex === 1) {
                            breakProject()
                        }
                    }
                })
                break;
            default:
        }


        const exitProject = () => {
            wx.showModal({
                title: '警告',
                content: `你即将退出${item.init ? item.project.projectName : '该项目'}，确定吗`,
                confirmColor: '#ff0000',
                success: res => {
                    if (res.confirm) {
                        wx.cloud.callFunction({
                            name: 'delCode',
                            data: {
                                userId: app.globalData.userInfo._id,
                                groupId: item._id
                            }
                        }).then(() => {
                            wx.showToast({
                                title: '已退出项目',
                                icon: 'none'
                            })
                            this.init();
                        })
                    }
                }
            })
        }

        const breakProject = () => {
            wx.showModal({
                title: '提示',
                content: '此操作将清除所有成员以及项目中的任务，您确定解散吗',
                success: (res) => {
                    if (res.confirm) {
                        wx.showModal({
                            title: '警告',
                            content: `您即将解散${item.init ? item.project.projectName : '该项目'}，您了解了吗`,
                            confirmText: '解散',
                            confirmColor: '#ff0000',
                            success: res => {
                                if (res.confirm) {
                                    wx.cloud.callFunction({
                                        name: 'breakGroup',
                                        data: {
                                            projectId: this.data.group._id
                                        }
                                    }).then(() => {
                                        this.init();
                                    })
                                }
                            }
                        })
                    }
                }
            })
        }
    }
})
let rangeTimer = null;
let rangeLocker = false;
let rangeLastStart = null;
let rangeLastEnd = null;
let rangeTask = null;